from sql_operation import MySqlOperation
import json

class CommentHandle:
    def __init__(self, conn=None):
        self.cur = MySqlOperation()
        self.conn = conn

    def teacher_get_comment(self, teacher_id):
        print(teacher_id)
        teacher_get_comment_sql = 'select c.comm_content, s.stu_name, c.comment_id ' \
                                  'from comment_info as c, stu_info as s ' \
                                  'where c.class_id in (select class_id from class_info where teacher_id = %s) ' \
                                  'and ' \
                                  's.stu_id = c.comm_user_id;' % teacher_id

        # print(teacher_get_comment_sql)
        try:
            self.cur.operation(teacher_get_comment_sql)
        except Exception as e:
            print('教师获取评论失败, 错误原因:', e)
            self.conn.send('500:获取评论内容失败, 请稍后尝试'.encode())
        else:
            sqlr = self.cur.fetch_all()
            print(sqlr)

            comm_key_list = ['comment', 'stu_name', 'comment_id']

            comm_list = []

            for comm in sqlr:
                comm_dict = {}
                for key_index in range(len(comm_key_list)):
                    comm_dict[comm_key_list[key_index]] = comm[key_index]

                comm_list.append(comm_dict)

            # print(comm_list)
            comm_json = json.dumps(comm_list)
            m = '200:%s' % comm_json

            self.conn.send(m.encode())

    def get_student_comment(self, student_id):
        print('学生评论被调用')
        print('传参:', student_id)

    def teacher_reply_comment(self, reply_content, reply_time, reply_msg_id):
        reply_insert_sql = 'insert into reply_comment(comment_id, reply_content, replay_time) values(%s, "%s", "%s")' \
                           % (reply_msg_id, reply_content, reply_time)
        print(reply_insert_sql)
        try:
            self.cur.operation(reply_insert_sql)
        except Exception as e:
            print('评论回复添加失败, 原因: %s' % e)
            self.cur.rollback()
            msg = '500:服务端添加评论失败, 请稍后再试'
            self.conn.send(msg.encode())
        else:
            print('OK')
            self.cur.commit()
            msg = '200:success'
            self.conn.send(msg.encode())

    # 获取对应老师课程的相关评论
    # select ci.*, rc.reply_content
    # from comment_info as ci, reply_comment as rc
    # where
    # ci.comment_id = rc.comment_id
    # and
    # ci.class_id in (select class_id from class_info where teacher_id = 2);

if __name__ == '__main__':
    a = CommentHandle()
    a.teacher_reply_comment('好的,谢谢', '20181111091012', '4')
    a.teacher_get_comment('2')